package com.seedeer.framework.web.handler;

import com.seedeer.common.constant.SymbolConsts;
import com.seedeer.common.exception.CustomException;
import com.seedeer.framework.i18n.I18nConsts;
import com.seedeer.framework.i18n.I18nUtil;
import com.seedeer.framework.web.domain.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.StringJoiner;

/**
 * 当controller抛出异常时, 自动捕获异常并返回相应错误码及信息
 *
 * @author wangqiang
 */
@RestControllerAdvice(annotations = {RestController.class, Controller.class}, basePackages = {"com.seedeer.project"})
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public AjaxResult handleMethodArgumentNotValid(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        StringJoiner errorMsg = new StringJoiner(SymbolConsts.SYMBOL_SEMICOLON_BLANK);
        bindingResult.getFieldErrors().forEach(fieldError -> errorMsg.add(String.format("错误字段: %s，错误值: %s，原因：%s" ,
                fieldError.getField(), fieldError.getRejectedValue(), fieldError.getDefaultMessage())));
        return AjaxResult.error(errorMsg.toString());
    }

    @ExceptionHandler(value = CustomException.class)
    public AjaxResult handleCustomException(CustomException e) {
        //若属于业务异常,则抛出相关编码信息
        String msg = I18nUtil.getMessage(e.getMessage(), e.getArgs());
        log.info(msg);
        return AjaxResult.error(e.getCode(), msg);
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public AjaxResult handleException(Exception e) {
        log.error(e.getMessage(), e);
        return AjaxResult.error(I18nUtil.getMessage(I18nConsts.SYSTEM_ERROR));
    }
}
